﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SysCommon.Tools;
using System.Reflection;

namespace SysCommon.UI
{


    public partial class DataGridViewForPageCtrl : UserControl
    {
        private delegate void MultiThreadAddDataGridViewRowDelegate(DataGridViewRow row);
        private delegate void MultiThreadClearDataGridViewRowsDelegate();
        public delegate object OnDataChangedHandler(object sender, OnDataChangedHandlerEventArgs e);
        /// <summary>
        /// 数据改变事件处理
        /// </summary>
        public event OnDataChangedHandler OnDataChangedHandlerEvent;
        string[] En_col;
        string[] Cn_col;
        public DataGridViewForPageCtrl()
        {
            InitializeComponent();
            try
            {
                this.btn_FirstPage.buttonBMPClick += new ButtonBMPClick(btn_FirstPage_Click);
                this.btn_LastPage.buttonBMPClick += new ButtonBMPClick(btn_LastPage_Click);
                this.btn_NextPage.buttonBMPClick += new ButtonBMPClick(btn_NextPage_Click);
                this.btn_PrePage.buttonBMPClick += new ButtonBMPClick(btn_PrePage_Click);

                this.cmb_PageCollection.TextChanged += new EventHandler(cmb_PageCollection_TextChanged);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用public DataGridViewForPageCtrl()出错", ex);
            }
        }

        /// <summary>
        /// 指示是否可以触发cmb_PageCollection的TextChanged事件
        /// </summary>
        private bool canSelectedIndexEventFire = true;
        /// <summary>
        /// 指示使用本控件前是否已进行初始化工作
        /// </summary>
        private bool isInit = false;
        /// <summary>
        /// 指示使用本控件前是否已进行初始化工作
        /// </summary>
        public bool IsInit
        {
            get { return isInit; }
        }

        #region 初始化图标
        /// <summary>
        /// 初始化图标
        /// </summary>
        /// <param name="FirstImage_A">第一页图标(鼠标不在其上)</param>
        /// <param name="FirstImage_B">第一页图标(鼠标在其上)</param>
        /// <param name="FirstImage_C">第一页图标(鼠标按下)</param>
        /// <param name="PreImage_A">前一页图标(鼠标不在其上)</param>
        /// <param name="PreImage_B">前一页图标(鼠标在其上)</param>
        /// <param name="PreImage_C">前一页图标(鼠标按下)</param>
        /// <param name="NextImage_A">下一页图标(鼠标不在其上)</param>
        /// <param name="NextImage_B">下一页图标(鼠标在其上)</param>
        /// <param name="NextImage_C">下一页图标(鼠标按下)</param>
        /// <param name="LastImage_A">最后页图标(鼠标不在其上)</param>
        /// <param name="LastImage_B">最后页图标(鼠标在其上)</param>
        /// <param name="LastImage_C">最后页图标(鼠标按下)</param>
        public void InitIco(Image FirstImage_A, Image FirstImage_B, Image FirstImage_C,
            Image PreImage_A, Image PreImage_B, Image PreImage_C,
            Image NextImage_A, Image NextImage_B, Image NextImage_C,
            Image LastImage_A, Image LastImage_B, Image LastImage_C)
        {
            try
            {
                this.btn_NextPage.Image_A = NextImage_A;
                this.btn_NextPage.Image_B = NextImage_B;
                this.btn_NextPage.Image_C = NextImage_C;

                this.btn_PrePage.Image_A = PreImage_A;
                this.btn_PrePage.Image_B = PreImage_B;
                this.btn_PrePage.Image_C = PreImage_C;

                this.btn_FirstPage.Image_A = FirstImage_A;
                this.btn_FirstPage.Image_B = FirstImage_B;
                this.btn_FirstPage.Image_C = FirstImage_C;

                this.btn_LastPage.Image_A = LastImage_A;
                this.btn_LastPage.Image_B = LastImage_B;
                this.btn_LastPage.Image_C = LastImage_C;

                //this.btn_NextPage.Width = image_A.Width;
                //this.btn_NextPage.Height = image_A.Height;

                //this.btn_PrePage.Width = image_A2.Width;
                //this.btn_PrePage.Height = image_A2.Height;
            }
            catch (Exception ex)
            {
                Global.mainLog.Error("初始化DataGridViewForPageCtrl出错", ex);
            }
        }
        #endregion

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="totalPageCount">总页数</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="data">数据</param>
        public void Init(int pageIndex, int totalPageCount, int pageSize, object data)
        {
            if (pageIndex <= 1)
            {
                btn_FirstPage.Enabled = false;
                btn_PrePage.Enabled = false;
            }
            if (!isInit)
            {
                TotalPageCount = totalPageCount;
                PageIndex = pageIndex;
                PageSize = pageSize;

                //dg_DataView.DataSource = data;
                SetDataResource(data);
                //return;
            }

            try
            {
                ////this.btn_FirstPage.buttonBMPClick += new ButtonBMPClick(btn_FirstPage_buttonBMPClick);
                //this.btn_FirstPage.buttonBMPClick += new ButtonBMPClick(btn_FirstPage_Click);
                //this.btn_LastPage.buttonBMPClick += new ButtonBMPClick(btn_LastPage_Click);
                //this.btn_NextPage.buttonBMPClick += new ButtonBMPClick(btn_NextPage_Click);
                //this.btn_PrePage.buttonBMPClick += new ButtonBMPClick(btn_PrePage_Click);

                //this.cmb_PageCollection.TextChanged += new EventHandler(cmb_PageCollection_TextChanged);

                TotalPageCount = totalPageCount;
                PageIndex = pageIndex;
                PageSize = pageSize;
                if (totalPageCount <= 1)
                {
                    this.btn_NextPage.Enabled = false;
                    this.btn_PrePage.Enabled = false;
                    this.btn_LastPage.Enabled = false;
                    this.btn_FirstPage.Enabled = false;
                }
                else
                {
                    this.btn_NextPage.Enabled = true;
                    //this.btn_PrePage.Enabled = true;
                    this.btn_LastPage.Enabled = true;
                    //this.btn_FirstPage.Enabled = true;
                }
                isInit = true;

                //dg_DataView.DataSource = data;
                SetDataResource(data);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用InitEvent()出错", ex);
            }
        }

        /// <summary>
        /// 初始化，加载指定页数据
        /// 并初始化DataGridView列表
        /// </summary>
        /// <param name="pageIndex">指定页码</param>
        /// <param name="totalPageCount">总页数</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="data">数据源（数组）</param>
        /// <param name="en_col">DataGridView Column Header 英文名称列表</param>
        /// <param name="cn_col">DataGridView Column Header 中文名称列表</param>
        public void Init(int pageIndex, int totalPageCount, int pageSize, object[] data,  string[] cn_col,string[] en_col)
        {
            En_col = en_col;
            Cn_col = cn_col;
            if (pageIndex <= 1)
            {
                btn_FirstPage.Enabled = false;
                btn_PrePage.Enabled = false;
            }
            else
            {
                btn_FirstPage.Enabled = true;
                btn_PrePage.Enabled = true;
            }
            if (pageIndex >= totalPageCount)
            {
                btn_NextPage.Enabled = false;
                btn_LastPage.Enabled = false;
            }
            else
            {
                btn_NextPage.Enabled = true;
                btn_LastPage.Enabled = true;
            }

            if (totalPageCount < pageIndex)
            {
                pageIndex = totalPageCount;
            }

            if (!isInit)
            {
                TotalPageCount = totalPageCount;
                PageIndex = pageIndex;
                PageSize = pageSize;

                ShowEntityForDataGridView.SetDefaultDataGrigStyle(this.dg_DataView);
                this.dg_DataView.Columns.Clear();

                ShowEntityForDataGridView.EntityToView(cn_col, en_col, data, this.dg_DataView);

                //this.dg_DataView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;

                //dg_DataView.DataSource = data;

                //return;

                //this.btn_FirstPage.buttonBMPClick += new ButtonBMPClick(btn_FirstPage_buttonBMPClick);
                //this.btn_FirstPage.buttonBMPClick += new ButtonBMPClick(btn_FirstPage_Click);
                //this.btn_LastPage.buttonBMPClick += new ButtonBMPClick(btn_LastPage_Click);
                //this.btn_NextPage.buttonBMPClick += new ButtonBMPClick(btn_NextPage_Click);
                //this.btn_PrePage.buttonBMPClick += new ButtonBMPClick(btn_PrePage_Click);

               
            }

            try
            {
                TotalPageCount = totalPageCount;
                PageIndex = pageIndex;
                PageSize = pageSize;

                isInit = true;
                this.dg_DataView.Columns.Clear();

                ShowEntityForDataGridView.EntityToView(cn_col, en_col, data, this.dg_DataView);
                //ShowEntityForDataGridView.EntityToView(cn_col, en_col, data, this.dg_DataView);
                //dg_DataView.DataSource = data;
                //SetDataResource(data);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用InitEvent()出错", ex);
            }
        }
        #endregion

        #region 数据源变更后处理函数
        /// <summary>
        /// 数据源变更后处理函数
        /// </summary>
        /// <param name="etys">变更后的数据</param>
        private void ChangeDataSource(object etys)
        {
            try
            {
                canSelectedIndexEventFire = false;
                //更改数据源
                //dg_DataView.DataSource = etys;
                SetDataResource(etys);

                //更改显示
                lbl_CurrentPage.Text = pageIndex.ToString();
                cmb_PageCollection.Text = pageIndex.ToString();

                //如果时第一页
                if (pageIndex <= 1)
                {
                    btn_FirstPage.Enabled = false;
                    btn_PrePage.Enabled = false;
                }
                else
                {
                    btn_FirstPage.Enabled = true;
                    btn_PrePage.Enabled = true;
                }

                //如果时最后一页
                if (pageIndex >= pageCount)
                {
                    btn_LastPage.Enabled = false;
                    btn_NextPage.Enabled = false;
                }
                else
                {
                    btn_LastPage.Enabled = true;
                    btn_NextPage.Enabled = true;
                }
                canSelectedIndexEventFire = true;

            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用ChangeDataSource(T[] etys)出错", ex);
            }
        }
        #endregion

        #region SetDataResource 在DataGridView中显示数据
        /// <summary> 
        /// 在DataGridView中显示数据
        /// </summary>
        /// <param name="data"></param>
        private void SetDataResource(object data)
        {
            try
            {

                #region 非空处理
                if (data is Array)
                {
                      Array array = data as Array;
                    if (array != null)
                    {
                        object[] a = array as object[];
                        ShowEntityForDataGridView.EntityToView(Cn_col, En_col,null , this.dg_DataView);
                        object ety = array.GetValue(0);
                        Type etyType = ety.GetType();

                        PropertyInfo[] ptys = new PropertyInfo[dg_DataView.Columns.Count];

                        for (int j = 0; j < dg_DataView.Columns.Count; j++)
                        {

                            ptys[j] = etyType.GetProperty(dg_DataView.Columns[j].Name);
                        }
                        DataGridViewRow row;
                        DataGridViewTextBoxCell cell;
                        row = new DataGridViewRow();
                     
                     
             
                     if (dg_DataView.InvokeRequired)
                        {
                            dg_DataView.Invoke(new MultiThreadClearDataGridViewRowsDelegate(delegate()
                            {
                                dg_DataView.Rows.Clear();
                            }));
                        }
                        else
                        //dg_DataView.DataSource = null;
                        {
                            if (dg_DataView.DataSource != null)
                            {
                                dg_DataView.DataSource = null;
                            }
                            else
                            {
                                dg_DataView.Rows.Clear();
                            }
                        }
                        ShowEntityForDataGridView.EntityToView(Cn_col, En_col, null, this.dg_DataView);
                        int len = array.Length;
                        for (int i = 0; i < len; i++)
                        {
                          
                            ety = array.GetValue(i);
                            row = new DataGridViewRow();
                            row.Tag = ety;
                            for (int k = 0; k < ptys.Length; k++)
                            {
                                if (ptys[k] != null)
                                {
                                    cell = new DataGridViewTextBoxCell();
                                    row.Cells.Add(cell);

                                    object value = ptys[k].GetValue(ety, null);

                                    if (value != null)
                                    {
                                        if (value is DateTime)
                                            if ((DateTime)value == default(DateTime))
                                                value = null;
                                            else
                                                value = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
                                    }
                                    cell.Value = value;
                                }
                                else
                                {
                                    DataGridViewCheckBoxCell cell2 = new DataGridViewCheckBoxCell(false);
                                    cell2.Value = true;
                                    row.Cells.Add(cell2);
                                }
                            }

                            if (dg_DataView.InvokeRequired)
                            {
                                dg_DataView.Invoke(new MultiThreadAddDataGridViewRowDelegate(delegate(DataGridViewRow dstRow)
                                {
                                    dg_DataView.Rows.Add(dstRow);
                                }), new object[] { row });
                            }
                            else
                            {
                                dg_DataView.Rows.Add(row);
                            }
                        }
                    }
                }
                #endregion
                else if (data == null)
                {
                    dg_DataView.Rows.Clear();
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用setDataResource出错", ex);
            }
        }
        #endregion

        #region 选择指定的页
        /// <summary>
        /// 选择指定的页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmb_PageCollection_TextChanged(object sender, EventArgs e)
        {
            if (isInit)
            {
                if (!canSelectedIndexEventFire) return;
                try
                {
                    if (OnDataChangedHandlerEvent != null)
                    {
                        string strText = cmb_PageCollection.Text.Trim();
                        if (strText.Length == 0)
                        {
                            return;
                        }
                        else
                        {
                            if (!IsNumber(strText)) return;
                        }

                        OnDataChangedHandlerEventArgs e1 = new OnDataChangedHandlerEventArgs();

                        e1.PageIndex = int.Parse(cmb_PageCollection.Text.Trim());
                        e1.TotalPageCount = pageCount;
                        e1.PageSize = pageSize;
                        e1.Action = OnDataChangedHandlerEventAction.SelectedPage;
                        object etys = OnDataChangedHandlerEvent(this, e1);
                        PageIndex = e1.PageIndex;

                        ChangeDataSource(etys);
                    }
                }
                catch (Exception ex)
                {
                    SysCommon.Global.mainLog.Error("调用出错", ex);
                }
            }
            else
            {
                SysCommon.Global.mainLog.Error("使用前未调用Init(int pageIndex,int totalPageCount,int pageSize,object data)初始化");
            }
        }
        #endregion

        #region 前一页鼠标按下
        /// <summary>
        /// 前一页鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_PrePage_Click(object sender, EventArgs e)
        {
            if (isInit)
            {
                try
                {
                    if (OnDataChangedHandlerEvent != null)
                    {
                        OnDataChangedHandlerEventArgs e1 = new OnDataChangedHandlerEventArgs();
                        pageIndex -= 1;

                        e1.PageIndex = pageIndex;
                        e1.TotalPageCount = pageCount;
                        e1.PageSize = pageSize;
                        e1.Action = OnDataChangedHandlerEventAction.PrePage;

                        object etys = OnDataChangedHandlerEvent(this, e1);

                        ChangeDataSource(etys);
                    }
                }
                catch (Exception ex)
                {
                    SysCommon.Global.mainLog.Error("调用出错", ex);
                }
            }
            else
            {
                SysCommon.Global.mainLog.Error("使用前未调用Init(int pageIndex,int totalPageCount,int pageSize,object data)初始化");
            }
        }
        #endregion

        #region 下一页鼠标按下
        /// <summary>
        /// 下一页鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_NextPage_Click(object sender, EventArgs e)
        {
            if (isInit)
            {
                try
                {
                    if (OnDataChangedHandlerEvent != null)
                    {
                        OnDataChangedHandlerEventArgs e1 = new OnDataChangedHandlerEventArgs();
                        pageIndex += 1;
                        e1.PageIndex = pageIndex;
                        e1.TotalPageCount = pageCount;
                        e1.PageSize = pageSize;
                        e1.Action = OnDataChangedHandlerEventAction.NextPage;
                        object etys = OnDataChangedHandlerEvent(this, e1);

                        ChangeDataSource(etys);
                    }
                }
                catch (Exception ex)
                {
                    SysCommon.Global.mainLog.Error("调用出错", ex);
                }
            }
            else
            {
                SysCommon.Global.mainLog.Error("使用前未调用Init(int pageIndex,int totalPageCount,int pageSize,object data)初始化");
            }
        }
        #endregion

        #region 最后一页鼠标按下
        /// <summary>
        /// 最后一页鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_LastPage_Click(object sender, EventArgs e)
        {
            if (isInit)
            {
                try
                {
                    if (OnDataChangedHandlerEvent != null)
                    {
                        OnDataChangedHandlerEventArgs e1 = new OnDataChangedHandlerEventArgs();
                        pageIndex = pageCount;

                        e1.PageIndex = pageCount;
                        e1.TotalPageCount = pageCount;
                        e1.PageSize = pageSize;
                        e1.Action = OnDataChangedHandlerEventAction.LastPage;
                        object etys = OnDataChangedHandlerEvent(this, e1);

                        ChangeDataSource(etys);
                    }
                }
                catch (Exception ex)
                {
                    SysCommon.Global.mainLog.Error("调用出错", ex);
                }
            }
            else
            {
                SysCommon.Global.mainLog.Error("使用前未调用Init(int pageIndex,int totalPageCount,int pageSize,object data)初始化");
            }
        }
        #endregion

        #region 第一页鼠标按下
        /// <summary>
        /// 第一页鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_FirstPage_Click(object sender, EventArgs e)
        {
            if (isInit)
            {
                try
                {
                    if (OnDataChangedHandlerEvent != null)
                    {
                        OnDataChangedHandlerEventArgs e1 = new OnDataChangedHandlerEventArgs();
                        pageIndex = 1;
                        e1.PageIndex = pageIndex;
                        e1.TotalPageCount = pageCount;
                        e1.PageSize = pageSize;
                        e1.Action = OnDataChangedHandlerEventAction.FirstPage;
                        object etys = OnDataChangedHandlerEvent(this, e1);

                        ChangeDataSource(etys);
                    }
                }
                catch (Exception ex)
                {
                    SysCommon.Global.mainLog.Error("调用出错", ex);
                }
            }
            else
            {
                SysCommon.Global.mainLog.Error("使用前未调用Init(int pageIndex,int totalPageCount,int pageSize,object data)初始化");
            }
        }
        #endregion

        #region 界面属性
        /// <summary>
        /// 当前页
        /// </summary>
        private int pageIndex;
        /// <summary>
        /// 当前页
        /// </summary>
        public int PageIndex
        {
            get { return pageIndex; }
            set
            {
                pageIndex = value;
                lbl_CurrentPage.Text = pageIndex.ToString();

                if (cmb_PageCollection.Items.Contains(pageIndex.ToString()))
                {
                    cmb_PageCollection.Text = pageIndex.ToString();
                }
            }
        }

        /// <summary>
        /// 总页数
        /// </summary>
        private int pageCount;
        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPageCount
        {
            get { return pageCount; }
            set
            {
                pageCount = value;
                lbl_TotalPage.Text = pageCount.ToString();

                cmb_PageCollection.Items.Clear();
                for (int i = 1; i <= pageCount; i++)
                {
                    cmb_PageCollection.Items.Add(i.ToString());
                }

                if (pageIndex != 0)
                {
                    cmb_PageCollection.Text = pageIndex.ToString();
                }
            }
        }

        /// <summary>
        /// 每页数量
        /// </summary>
        private int pageSize;
        /// <summary>
        /// 每页数量
        /// </summary>
        public int PageSize
        {
            get { return pageSize; }
            set
            {
                pageSize = value;
                lbl_PageSize.Text = "每页" + pageSize + "条";
            }
        }
        #endregion

        #region 其他辅助类
        public class OnDataChangedHandlerEventArgs
        {
            /// <summary>
            /// 当前页
            /// </summary>
            private int pageIndex;
            /// <summary>
            /// 当前页
            /// </summary>
            public int PageIndex
            {
                get { return pageIndex; }
                set
                {
                    pageIndex = value;
                }
            }

            /// <summary>
            /// 总页数
            /// </summary>
            private int pageCount;
            /// <summary>
            /// 总页数
            /// </summary>
            public int TotalPageCount
            {
                get { return pageCount; }
                set
                {
                    pageCount = value;
                }
            }

            /// <summary>
            /// 每页数量
            /// </summary>
            private int pageSize;
            /// <summary>
            /// 每页数量
            /// </summary>
            public int PageSize
            {
                get { return pageSize; }
                set
                {
                    pageSize = value;
                }
            }

            private OnDataChangedHandlerEventAction action;
            /// <summary>
            /// 事件类型
            /// </summary>
            public OnDataChangedHandlerEventAction Action
            {
                get { return action; }
                set { action = value; }
            }
        }

        public enum OnDataChangedHandlerEventAction
        {
            FirstPage,
            PrePage,
            NextPage,
            LastPage,
            SelectedPage
        }
        #endregion

        bool IsNumber(string str)
        {
            foreach (char c in str)
            {
                if (char.IsNumber(c))
                {
                    continue;
                }

                return false;
            }
            return true;
        }

        private void cmb_PageCollection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isInit)
            {
                if (!canSelectedIndexEventFire) return;
                try
                {
                    if (OnDataChangedHandlerEvent != null)
                    {
                        string strText = cmb_PageCollection.Text.Trim();
                        if (strText.Length == 0)
                        {
                            return;
                        }
                        else
                        {
                            if (!IsNumber(strText)) return;
                        }

                        OnDataChangedHandlerEventArgs e1 = new OnDataChangedHandlerEventArgs();

                        e1.PageIndex = int.Parse(cmb_PageCollection.Text.Trim());
                        e1.TotalPageCount = pageCount;
                        e1.PageSize = pageSize;
                        e1.Action = OnDataChangedHandlerEventAction.SelectedPage;
                        object etys = OnDataChangedHandlerEvent(this, e1);
                        PageIndex = e1.PageIndex;

                        ChangeDataSource(etys);
                    }
                }
                catch (Exception ex)
                {
                    SysCommon.Global.mainLog.Error("调用出错", ex);
                }
            }
            else
            {
                SysCommon.Global.mainLog.Error("使用前未调用Init(int pageIndex,int totalPageCount,int pageSize,object data)初始化");
            }
        }
    }
}
